package com.qire.manhua.model.viewModel.impl;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.IBinder;
import android.view.View;
import android.widget.BaseAdapter;

import com.qire.common.SummerApp;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.BookshelfDownloadController;
import com.qire.manhua.dal.service.HomeBookshelfDownloadService;
import com.qire.manhua.databinding.LayoutHomeBookshelfDownloadItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.service.ComicDownloadService;
import com.qire.manhua.service.ComicDownloadService.ProgressObserver;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.MutableLiveData;

public class BookshelfDownloadViewModel extends BaseViewModel {

    private final HomeBookshelfDownloadService downloadService = new HomeBookshelfDownloadService(this);

    private final ArrayList<DownloadItemViewModel> downloadList = new ArrayList();

    private final SummerBindAdapter<DownloadItemViewModel> downloadAdapter = new SummerBindAdapter(downloadList);

    private FragmentActivity activity;

    private boolean isEditing = false;

    private final ArrayList<Integer> batchDeleteList = new ArrayList<>();

    private final ProgressObserver progressObserver = comicChapter -> {
        for(DownloadItemViewModel itemViewModel : downloadList) {
            if(itemViewModel.compare(comicChapter.getComicId())) {
                itemViewModel.updateState(comicChapter.getId(), comicChapter.getDownloadState());
            }
        }
    };

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        ComicDownloadService.ComicDownloadBinder comicDownloadBinder;
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            comicDownloadBinder = (ComicDownloadService.ComicDownloadBinder) service;
            comicDownloadBinder.addObserver(progressObserver);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if(ObjectUtil.nonNull(comicDownloadBinder)) {
                comicDownloadBinder.removeObserver(progressObserver);
            }
        }
    };

    private BookshelfViewModel bookshelfViewModel;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     */
    public void onAddition(FragmentActivity activity, BookshelfDownloadController controller) {
        this.activity = activity;
        downloadAdapter.setEventProcess(controller);
//        refreshUI();
        bindDownloadService();
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        unBindDownloadService();
        this.activity = null;
        downloadAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #数据 begin
    public void loadDownloadData() {
        downloadService.loadLocalDownloadData();
    }

    public void clearDownloadList() {
        downloadList.clear();
        // 防止状态不同步，由于页面切换回收、其他页面追加下载任务等情况会导致下载项目列表重新生成并刷新状态。
        // 如果删除选项没有清楚会导致UI于删除内容不同步的问题。如果复杂情况下应该使用实时计算来获取选中的删除项个数。
        batchDeleteList.clear();
    }
    public DownloadItemViewModel buildDownloadItemViewModel(int comicId, String comicName, String comicCover) {
        return new DownloadItemViewModel(comicId, comicName, comicCover);
    }
    public void addDownloadItemViewModel(DownloadItemViewModel itemViewModel) {
        downloadList.add(itemViewModel);
    }

    public void bindDownloadService() {
        ComicDownloadService.bindService(activity, serviceConnection);
    }

    public void unBindDownloadService() {
        ComicDownloadService.unBindService(activity, serviceConnection);
    }

    public void updateDownloadService(int downloadActionFlags, int... chapterIds) {
        ComicDownloadService.startService(SummerApp.summerApp(), downloadActionFlags, chapterIds);
    }

    /**
     * 批量删除下载记录：<br />
     * 1.遍历所有选中漫画，暂停正在下载的任务；<br />
     * 2.遍历删除所有选择漫画章节数据库记录；<br />
     * 3.遍历删除所有选择漫画下载记录；<br />
     * 4.遍历删除所有选择的漫画下载目录文件
     */
    public void batchDelDownloadRecord() {
        // 停止下载服务
        for(int comicId : batchDeleteList) {
            for(DownloadItemViewModel itemViewModel : downloadList) {
                if(itemViewModel.compare(comicId) && itemViewModel.isDownloading()) {
                    itemViewModel.toggleDownloadStatus();
                }
            }
        }
        // 删除数据库、文件
        downloadService.batchDeleteDownloadRecord(batchDeleteList.toArray(new Integer[0]));
        // 删除操作后列表列表没有可选数据时退出编辑状态
        if(ObjectUtil.nonNull(bookshelfViewModel) && batchDeleteList.size() >= downloadList.size()) {
            bookshelfViewModel.closeEditMode();
        }
    }

    /**
     * 根据当前编辑状态判断下一步切换编辑状态的条件，如果没有可操作选项，则不允许进入编辑页。
     * @return true 为可进入编辑，false 不可进入编辑，只有当编辑状态位 false 且 收藏有内容时才可以编辑。
     */
    public boolean isAllowEdit() {
        return !isEditing && ListUtil.notEmpty(downloadList);
    }

    public int batchDeleteCount() {
        return batchDeleteList.size();
    }

    //endregion #数据 end

    //region    #UI操作 begin

    public void setBookshelfViewModel(BookshelfViewModel bookshelfViewModel) {
        this.bookshelfViewModel = bookshelfViewModel;
        if(ObjectUtil.nonNull(bookshelfViewModel)) {
            bookshelfViewModel.toggleAllCheckUI(batchDeleteCount() >= downloadList.size());
        }
    }

    public void refreshUI() {
        refreshEmptyDataUI();
        refreshDeletePlateUI();
        downloadAdapter.notifyDataSetChanged();
    }

    public void refreshEmptyDataUI() {
        boolean isEmpty = ListUtil.isEmpty(downloadList);
        isEditing = isEmpty ? false : isEditing;
        set("panelPageNumber", isEmpty ? 0 : 1);
        set("exceptionBtnText", "去书城看看");
    }

    public void refreshDeletePlateUI() {
        set("deletePlateVisible", isEditing ? View.VISIBLE : View.GONE);

        boolean isActive = ListUtil.notEmpty(batchDeleteList);

        set("deleteButtonIconColor", isActive ? ColorStateList.valueOf(Color.rgb(0xff, 0x90, 0x24)) : ColorStateList.valueOf(Color.rgb(0x5c,0x5c,0x5c)));
        set("deleteButtonText", "删除选中(" + batchDeleteCount() +")");
        set("deleteButtonTextColor", isActive ? "#ff9024" : "#5c5c5c");

        // 刷新父框架面板
        if(ObjectUtil.nonNull(bookshelfViewModel)) {
            bookshelfViewModel.toggleAllCheckUI(batchDeleteCount() >= downloadList.size());
        }
    }

    /**
     * 切换编辑状态
     * @param isEditMode true 进入编辑状态  false 退出编辑状态
     */
    public void toggleEditing(boolean isEditMode) {
        this.isEditing = isEditMode;
        refreshUI();
        if(!isEditing) {
            // 如果是退出编辑，则清空所有选中状态
            for(DownloadItemViewModel itemViewModel : downloadList) {
                if(itemViewModel.isWhetherChoose()) {
                    itemViewModel.toggleWhetherChoose();
                }
            }
        }
    }

    /**
     * 切换所有下载项选择状态
     */
    public void toggleCheckAll() {
        boolean isCheck = batchDeleteCount() == downloadList.size();
        for(DownloadItemViewModel itemViewModel : downloadList) {
            if(isCheck == itemViewModel.isWhetherChoose()) {
                itemViewModel.toggleWhetherChoose();
            }
        }
    }
    //endregion #UI操作 end

    //region    #UI绑定 begin

    public MutableLiveData<Integer> getPanelPageNumber() {
        return get("panelPageNumber");
    }

    public MutableLiveData<CharSequence> getExceptionBtnText() {
        return get("exceptionBtnText");
    }

    public MutableLiveData<Integer> getDeletePlateVisible() {
        return get("deletePlateVisible");
    }
    public MutableLiveData<ColorStateList> getDeleteButtonIconColor() {
        return get("deleteButtonIconColor");
    }
    public MutableLiveData<CharSequence> getDeleteButtonText() {
        return get("deleteButtonText");
    }
    public MutableLiveData<String> getDeleteButtonTextColor() {
        return get("deleteButtonTextColor");
    }

    public BaseAdapter getDownloadAdapter() {
        return downloadAdapter;
    }

    //endregion #UI绑定 end

    @AdapterEntityBind(viewRid = R.layout.layout_home_bookshelf_download_item)
    public class DownloadItemViewModel extends BaseObservable implements AutoVariable<LayoutHomeBookshelfDownloadItemBinding> {

        private final int    comicId;
        private final String comicName;
        private final String comicCover;

        private final ArrayList<ChapterWrapper> chapterWrapperList = new ArrayList<>();

        private volatile int completeCount;

        private boolean isWhetherChoose = false;

        public DownloadItemViewModel(int comicId, String comicName, String comicCover) {
            this.comicId = comicId;
            this.comicName = comicName;
            this.comicCover = comicCover;
        }

        @Override
        public void bindVariable(LayoutHomeBookshelfDownloadItemBinding viewBind) {
            viewBind.setDownloadItemViewModel(this);
        }

        public void resetChapterWrapper() {
            this.chapterWrapperList.clear();
            this.completeCount = 0;
        }

        public void addChapterWrapper(int chapterId, int downloadState) {
            this.chapterWrapperList.add(new ChapterWrapper(chapterId).updateDownLoadState(downloadState));
        }

        public boolean compare(int comicId) {
            return this.comicId == comicId;
        }

        public void updateState(int chapterId, int downloadState) {
            for(ChapterWrapper wrapper : chapterWrapperList) {
                if(wrapper.chapterId == chapterId) {
                    wrapper.updateDownLoadState(downloadState);
                    notifyChange();
                    return;
                }
            }
        }

        public int allCount() {
            return chapterWrapperList.size();
        }

        public int completeCount() {
            int completeCount = 0;
            for(ChapterWrapper wrapper : chapterWrapperList) {
                if(wrapper.isComplete()) {
                    completeCount++;
                }
            }
            return completeCount;
        }

        public boolean isComplete() {
            for(ChapterWrapper chapterWrapper : chapterWrapperList) {
                if(!chapterWrapper.isComplete()) {
                    return false;
                }
            }
            return true;
        }

        public boolean isDownloading() {
            for(ChapterWrapper chapterWrapper : chapterWrapperList) {
                if(chapterWrapper.isDownloading()) {
                    return true;
                }
            }
            return false;
        }

        public void toggleDownloadStatus() {
            if(isComplete()) {
                return;
            }

            final boolean isDownloading = isDownloading();

            int downloadActionFlags = isDownloading ? ComicDownloadService.ACTION_PAUSE : ComicDownloadService.ACTION_START;

            int chapterCount = chapterWrapperList.size();
            int[] chapterIds = new int[chapterCount];

            for(int index = 0; index < chapterCount; index++) {
                chapterIds[index] = chapterWrapperList.get(index).chapterId;
            }

            updateDownloadService(downloadActionFlags, chapterIds);

        }

        public boolean isEditMode() {
            return isEditing;
        }

        public boolean isWhetherChoose() {
            return isWhetherChoose;
        }

        public void toggleWhetherChoose() {
            isWhetherChoose = !isWhetherChoose;
            if(isWhetherChoose) {
                batchDeleteList.add(comicId);
            } else {
                batchDeleteList.remove(Integer.valueOf(comicId));
            }
            notifyPropertyChanged(BR.itemViewBgColor);
            notifyPropertyChanged(BR.checkBoxImgRid);
            refreshDeletePlateUI();
        }

        public ComicBookEntity toComicBookEntity() {
            ComicBookEntity comicBookEntity = new ComicBookEntity(comicId, comicName);
            comicBookEntity.setCoverPlotVertical(comicCover);
            return comicBookEntity;
        }

        //region    #UI绑定 begin
        @Bindable
        public String getItemViewBgColor() {
            if(!isEditing) {
                return "#ffffff";
            }
            return isWhetherChoose ? "#fffdf5" : "#ffffff";
        }

        @Bindable
        public String getComicCover() {
            return comicCover;
        }

        @Bindable
        public int getCheckBoxVisible() {
            return isEditing ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public int getCheckBoxImgRid() {
            return isWhetherChoose ? R.drawable.app_home_bookshelf_select_b : R.drawable.app_home_bookshelf_select_a;
        }

        @Bindable
        public CharSequence getTitleText(){
            return comicName;
        }

        @Bindable
        public int getProgressBarMax() {
            return allCount();
        }
        @Bindable
        public int getProgressBarValue() {
            return completeCount();
        }
        @Bindable
        public CharSequence getDownloadStatusText() {
            String progressText = "(" + completeCount() + "/" + allCount() + ")";
            if(isComplete()) {
                return "已完成 " + progressText;
            }
            if(isDownloading()) {
                return "下载中 " + progressText;
            }
            return "已暂停 " + progressText;
        }

        @Bindable
        public CharSequence getOperationBtnText() {
            if(isDownloading()) {
                return "暂停";
            }
            if(isComplete()) {
                return "阅读";
            }
            return "继续";
        }
        @Bindable
        public int getOperationBtnBgRid() {
            if(isComplete()) {
                return R.drawable.app_home_bookshelf_item_button_yellow;
            }
            return R.drawable.app_home_bookshelf_item_button_gray;
        }
        @Bindable
        public int getOperationBtnVisible() {
            return isEditing ? View.GONE : View.VISIBLE;
        }
        //endregion #UI绑定 end

        public class ChapterWrapper {

            public static final int STATE_RUNNING = 0;
            public static final int STATE_PAUSE = 1;
            public static final int STATE_COMPLETE = 2;

            private final int chapterId;
            private int downloadState;

            public ChapterWrapper(int chapterId) {
                this.chapterId = chapterId;
            }

            public ChapterWrapper updateDownLoadState(int downloadState) {
                this.downloadState = downloadState;
                return this;
            }

            public boolean isComplete() {
                return downloadState == STATE_COMPLETE;
            }

            public boolean isPause() {
                return downloadState == STATE_PAUSE;
            }

            public boolean isDownloading() {
                return downloadState == STATE_RUNNING;
            }
        }

    }

}
